<template>
  <div class="main">
    <div class="userMain">
      <!-- 面包屑 -->
      <app-link :name="title"></app-link>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="searchForm.name" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.sex" placeholder="性别">
            <el-option label="女" value="女"></el-option>
            <el-option label="男" value="男"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getName()" icon="el-icon-search">查询</el-button>
          <el-button type="primary" @click="reset" icon="el-icon-refresh-right">重置</el-button>
          <el-button type="primary" @click="addUser" icon="el-icon-circle-plus">新增</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户列表页 -->
      <el-table :data="list" border style="width: 100%" stripe>
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="username" label="真实姓名" width="120"></el-table-column>
        <el-table-column prop="password" label="密码" width="120"></el-table-column>
        <el-table-column prop="sex" label="性别" width="80"></el-table-column>
        <el-table-column prop="iphone" label="电话号码" width="140"></el-table-column>
        <el-table-column prop="birthday" label="出生日期" width="120"></el-table-column>
        <el-table-column label="头像" width="80">
          <template slot-scope="scope">
            <!-- scope指整个数据对象。scope.row指当前行数据 scope.row.avatar -->
            <img :src="scope.row.img" alt style="width:50px;height:50px;" />
          </template>
        </el-table-column>
        <el-table-column prop="addr" label="地址" width="280"></el-table-column>
        <el-table-column label="操作" width="220px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="editUser(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-show="pages > 1"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10,20,30,40]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!-- 对话框 新增 -->
      <el-dialog :title="isAdd ? '添加用户' : '编辑用户'" :visible.sync="dialogFormVisible" width="500px">
        <el-form
          :rules="rules"
          :model="ruleForm"
          label-position="right"
          label-width="80px"
          class="demo-ruleForm"
          ref="ruleForm"
        >
          <el-form-item label="真实姓名" prop="username">
            <el-input
              v-model="ruleForm.username"
              autocomplete="off"
              placeholder="请输入姓名"
              style="width:300px"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="ruleForm.sex" placeholder="性别" style="width:80px">
              <el-option label="女" value="女"></el-option>
              <el-option label="男" value="男"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="ruleForm.password"
              autocomplete="off"
              placeholder="请输入密码"
              style="width:300px"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="iphone">
            <el-input
              v-model.trim="ruleForm.iphone"
              autocomplete="off"
              style="width:300px"
              placeholder="请输入手机号码"
            ></el-input>
          </el-form-item>
          <el-form-item label="出生日期" prop="birthday">
            <el-date-picker
              v-model="ruleForm.birthday"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
              style="width:200px"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="地址" prop="addr">
            <el-input
              v-model="ruleForm.addr"
              autocomplete="off"
              style="width:300px"
              placeholder="请输入地址"
            ></el-input>
          </el-form-item>
          <el-form-item label="上传头像">
            <el-upload
              class="upload-demo"
              ref="upload"
              action="/dev-api/userinf/handphoto"
              :file-list="fileList"
              :http-request="httpRequest"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="onChange"
              :before-remove="beforeRemove"
              :on-exceed="handleExceed"
              multiple
              :limit="1"
              name
              :auto-upload="false"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="isAdd ? add() : edit()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import appLink from "@/components/link";
import userApi from "@/api/userApi";
export default {
  data() {
    var validatePsw = (rule, value, callback) => {
      /*
        value:该表单的value值
        callback：回调函数，返回提示信息
      */
      let reg = /1[3-9]\d{9}/;
      if (reg.test(value) && value.length == 11) {
        userApi.checkIphone(value).then(res => {
          if (res.data.flag) {
            callback();
          } else {
            callback(new Error("手机号码已被注册过，请重新输入新的手机号码"));
          }
        });
      } else {
        callback(new Error("请输入正确的手机号码"));
      }
    };

    return {
      title: "用户管理",
      searchForm: {
        name: "",
        sex: ""
      }, //查询条件
      list: [
        // {
        //   date: "2016-05-02",
        //   name: "王小虎",
        //   sex: "男",
        //   phone: "15888945656",
        //   birthday: "2000-10-12",
        //   address: "上海市普陀区金沙江路 1518 弄"
        // },
        // {
        //   date: "2016-05-04",
        //   name: "王小虎",
        //   sex: "男",
        //   phone: "15888945656",
        //   birthday: "2000-10-12",
        //   address: "上海市普陀区金沙江路 1517 弄"
        // },
        // {
        //   date: "2016-05-01",
        //   name: "王小虎",
        //   sex: "男",
        //   phone: "15888945656",
        //   birthday: "2000-10-12",
        //   address: "上海市普陀区金沙江路 1519 弄"
        // }
      ],

      // currentPage4: 4,
      page: 1, //当前页
      pagesize: 10, //一页多少条
      total: 0, //总条数
      pages: 0, //总页数
      dialogFormVisible: false, //弹窗开关

      rules: {
        username: [
          { required: true, message: "姓名不能为空", trigger: "blur" } //真实姓名不能为空
        ],
        iphone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          { validator: validatePsw, trigger: "blur" }
        ],
        password: [{ required: true, message: "密码不能为空", trigger: "blur" }]
      }, //表单验证
      ruleForm: {
        username: "",
        sex: "",
        password: "",
        iphone: "",
        birthday: "",
        addr: ""
      },
      isAdd: true, //对话框类别初始框 ture：添加用户
      fileList: []
    };
  },

  components: { appLink },

  methods: {
    //功能：进入页面就发送请求，获取用户列表渲染
    async fetchall() {
      try {
        let p = await userApi.getList(this.page, this.pagesize);
        console.log(p.data);
        if (p.data.flag) {
          // //查询到了
          this.list = p.data.data; //数据部分
          this.total = p.data.total; //总条数
          this.pages = p.data.pages;
        } else {
          this.$message({
            message: "找不到该数据，换个条件试一试",
            type: "warnning"
          });
        }
      } catch (err) {
        console.log(err);
      }
    },

    // 功能：模糊查询
    async getName() {
      try {
        let p = await userApi.getName(
          this.searchForm.name,
          this.searchForm.sex
        );
        console.log(p.data, "@@@@@@@@");
        if (p.data.flag) {
          // //查询到了
          this.list = p.data.data; //数据部分
          this.total = p.data.total; //总条数
          this.pages = Math.ceil(p.data.total / p.data.pagesize);
        } else {
          this.$message({
            message: "找不到该数据，换个条件试一试",
            type: "warnning"
          });
        }
      } catch (err) {
        console.log(err);
      }
    },

    //重置按钮
    reset() {
      this.searchForm = {};
      this.fetchall();
    },

    //功能：点击打开新增弹窗
    addUser() {
      this.isAdd = true; //添加用户，开关设置为true
      this.dialogFormVisible = true;
      // this.ruleForm = {};
      this.fileList = []; //清空图片列表
      this.$nextTick(() => {
        // this.$nextTick()它是一个异步事件，当渲染结束 之后 ，它的回调函数才会被执行
        // 弹出窗口打开之后 ，需要加载Dom, 就需要花费一点时间，我们就应该等待它加载完dom之后，再进行调用resetFields方法，重置表单和清除样式
        this.$refs["ruleForm"].resetFields();
        this.ruleForm = {};
      });
    },

    //功能：点击打开可编辑的弹窗
    editUser(row) {
      console.log(row, 999);
      this.isAdd = false; //编辑弹窗设置为false
      this.fileList = [];
      this.dialogFormVisible = true; //打开弹窗
      this.ruleForm = row;
      let obj = {
        name: this.ruleForm.fileNames,
        url: this.ruleForm.img
      };
      this.fileList.push(obj);
    },

    //功能：点击确定按钮，修改用户信息
    edit() {
      console.log("修改数据");
      this.$refs.upload.submit(); //上传图片

      //正则校验通过：运行上传数据添加新用户
      let form1 = new FormData();
      // console.log(form, 555555);

      form1.append("username", this.ruleForm.username);
      form1.append("sex", this.ruleForm.sex);
      form1.append("iphone", this.ruleForm.iphone);
      form1.append("birthday", this.ruleForm.birthday);
      form1.append("addr", this.ruleForm.addr);
      // form.append("id", this.ruleForm.id);
      //  form.append("atavar", this.ruleForm.addr);
      console.log(form1, 666);
      console.log(this.fileList[0]);

      this.fileList.forEach(file => {
        console.log(file.url, "22222");

        //此处一定是append file.raw 上传文件只需维护fileList file.raw.name要加上
        form1.append("avatar", file.raw);
        // console.log(file.raw, "666");
        form1.append("fileNames", file.name);
        // console.log(fileNames);
      });

      console.log(form1, 66666666);

      let p = userApi.editPhoto(this.ruleForm.id, form1).then(res => {
        // console.log(this.ruleForm.id);
        console.log(res.data);
        if (res.data.flag) {
          //修改成功
          this.$message({
            message: "修改成功",
            type: "success"
          });

          //关闭弹窗并刷新页面
          this.dialogFormVisible = false;
          this.fetchall();
        } else {
          //修改失败
          this.$message({
            message: "修改失败",
            type: "error"
          });
        }
      });
    },

    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.page = 1;
      this.fetchall();
    },
    // 分页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.fetchall();
    },

    //功能：添加新用户：确定的时候，把内容提交给后台
    add() {
      this.$refs.ruleForm.validate(async res => {
        console.log(res);
        if (res) {
          //手动提交图片的关键
          this.$refs.upload.submit(); //上传图片
          console.log(this.$refs, 999);
          //正则校验通过：运行上传数据添加新用户
          let form = new FormData();
          form.append("username", this.ruleForm.username);
          form.append("password", this.ruleForm.password);
          form.append("sex", this.ruleForm.sex);
          form.append("iphone", this.ruleForm.iphone);
          form.append("birthday", this.ruleForm.birthday);
          form.append("addr", this.ruleForm.addr);
          //  form.append("atavar", this.ruleForm.addr);
          console.log(form);

          this.fileList.forEach(file => {
            //此处一定是append file.raw 上传文件只需维护fileList file.raw.name要加上
            form.append("avatar", file.raw);
            form.append("fileNames", file.name);
            // console.log(fileNames);
            console.log(file.raw, "#####################");
          });

          try {
            let p = await userApi.addUser(form);
            console.log(form);

            console.log(p.data);

            if (p.data.flag) {
              //提交成功
              this.$message({
                message: "添加成功",
                type: "success"
              });
              this.dialogFormVisible = false; //关闭弹窗
            } else {
              this.$message({
                message: "添加失败",
                type: "error"
              });
            }
          } catch (err) {
            console.log(err);
          }
        } else {
          //校验没通过：不能提交
          this.$message({
            message: "注意书写条件哦",
            type: "error"
          });
        }
      });
    },

    //功能：删除一个用户
    delUser(row) {
      console.log(row.id);
      this.$confirm("此操作将永久删除该用户吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //点击确定：真的删除
          userApi.delUser(row.id).then(res => {
            if (res.data.flag) {
              //修改成功
              this.$message({
                message: "删除成功",
                type: "success"
              });

              //刷新页面
              this.fetchall();
            } else {
              //修改失败
              this.$message({
                message: "删除失败",
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //功能： 文件上传（上传头像）
    httpRequest(file) {
      // console.log(666)
    },
    onChange(file, fileList) {
      this.fileList = fileList;
    },
    //功能：删除已上传的图片
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      let url = file.url;
      console.log(this.ruleForm.id, url);
      userApi.delPhoto(this.ruleForm.id).then(res => {
        console.log(888);
      });
    },

    handlePreview(file) {
      console.log(file);
    },
    //功能：选择图片超过规定提示
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },

    //功能：删除图片前提示
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    }
  },

  created() {
    this.fetchall(); //进入页面就发起请求
    // console.log(ruleForm.img);
  }
};
</script>

<style>
.el-form {
  margin-top: 20px;
}
.el-pagination {
  text-align: center;
  margin-top: 30px;
  margin-bottom: 50px;
}
.el-pagination .el-pager li {
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  /* background: #ccc; */
  margin-right: 5px;
}
.userMain .el-pagination .el-pager li:hover {
  border: 1px solid #409eff;
}
.userMain .el-pagination .el-pager .active {
  background: #409eff;
  color: #fff;
  cursor: pointer;
}
.userMain .line {
  border-left: 5px solid #409eff;
}
</style>
